package com.das.mechanic_base.mvp.view.camera;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.das.mechanic_base.R;
import com.das.mechanic_base.R2;
import com.das.mechanic_base.app.X3AppRouterConstants;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.base.X3BaseActivity;
import com.das.mechanic_base.base.X3BasePresenter;
import com.das.mechanic_base.bean.camera.CameraBean;
import com.das.mechanic_base.bean.even.DeleteFriends;
import com.das.mechanic_base.utils.X3FileUtils;
import com.das.mechanic_base.utils.X3ScreenUtils;
import com.das.mechanic_base.utils.X3StatusBarUtil;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.X3ToastUtils;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.otaliastudios.cameraview.CameraListener;
import com.otaliastudios.cameraview.CameraView;
import com.otaliastudios.cameraview.PictureResult;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = X3AppRouterConstants.Router.MAIN_CUT)
public class X3MainCarCutActivity extends X3BaseActivity {

    @BindView(R2.id.cv_view)
    CameraView cv_view;
    @BindView(R2.id.iv_image)
    ImageView iv_image;
    @BindView(R2.id.tv_next)
    TextView tv_next;
    @BindView(R2.id.iv_close)
    ImageView iv_close;
    @BindView(R2.id.iv_photo)
    ImageView iv_photo;
    @BindView(R2.id.iv_back)
    ImageView iv_back;
    @BindView(R2.id.iv_cut)
    ImageView iv_cut;
    @BindView(R2.id.tv_sample)
    TextView tv_sample;
    @BindView(R2.id.tv_resize)
    TextView tv_resize;

    private long carId;
    private String carNum;
    private File imgFile;

    @Override
    protected int getLayoutId() {
        EventBus.getDefault().register(this);

        return R.layout.x3_activity_main_car_cut;
    }

    @Override
    protected void initView() {
        X3StatusBarUtil.darkMode(this);

        carId = getIntent().getLongExtra("carId", 0L);
        carNum = getIntent().getStringExtra("carNum");
        initCamera();
        cv_view.setUseDeviceOrientation(true);

        tv_next.post(() -> {
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) tv_next.getLayoutParams();
            layoutParams.bottomMargin = tv_next.getWidth() / 2;
            layoutParams.leftMargin = -tv_next.getWidth() / 2 + X3ScreenUtils.dipToPx(44, X3MainCarCutActivity.this);
            tv_next.setLayoutParams(layoutParams);
            tv_next.setVisibility(View.INVISIBLE);
        });
    }

    private void initCamera() {
        XXPermissions.with(this)
                .permission(Permission.CAMERA)
                .permission(Permission.Group.STORAGE)
                .permission(Permission.RECORD_AUDIO)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if(all){
                            cv_view.setLifecycleOwner(X3MainCarCutActivity.this);
                        }else {
                            XXPermissions.startPermissionActivity(X3MainCarCutActivity.this,permissions);
                        }

                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        XXPermissions.startPermissionActivity(X3MainCarCutActivity.this,permissions);
                    }
                });

        cv_view.addCameraListener(new CameraListener() {
            @Override
            public void onPictureTaken(@NonNull PictureResult result) {
                super.onPictureTaken(result);

                imgFile = new File(X3FileUtils.getStoragePath(X3MainCarCutActivity.this, X3FileUtils.CAR_STORAGE_PATH) + "CarCut" + System.currentTimeMillis() + ".jpg");
                if (!imgFile.exists()) {
                    try {
                        imgFile.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                result.toFile(imgFile, file -> {
                    if (imgFile == null) {
                        X3ToastUtils.showMessage(getString(R.string.x3_camera_error));
                        return;
                    }
                    Bitmap bitmap = X3FileUtils.rotaImageView(90, BitmapFactory.decodeFile(imgFile.getPath()));
                    iv_image.setImageBitmap(bitmap);
                    cv_view.setVisibility(View.GONE);
                    iv_image.setVisibility(View.VISIBLE);
                    tv_next.setVisibility(View.VISIBLE);
                    iv_photo.setVisibility(View.INVISIBLE);
                    iv_back.setVisibility(View.GONE);
                    iv_close.setVisibility(View.VISIBLE);
                    iv_cut.setVisibility(View.GONE);

//                    GlideNewUtils.loadNormalImage(MainCarCutActivity.this,imgFile.getPath(),iv_image, Color.BLACK);
                });

            }
        });
    }

    @Override
    protected X3BasePresenter createPresenter() {
        return null;
    }

    @OnClick({R2.id.iv_back,R2.id.iv_cut,R2.id.iv_photo,R2.id.iv_close,R2.id.tv_next})
    public void onViewClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            finish();
        } else if (id == R.id.iv_cut) {
            cv_view.takePictureSnapshot();
        } else if (id == R.id.iv_photo) {// 跳转到相册选取图片
            autoObtainStoragePermission();
        } else if (id == R.id.iv_close) {
            cv_view.setVisibility(View.VISIBLE);
            iv_image.setVisibility(View.GONE);
            tv_next.setVisibility(View.INVISIBLE);
            iv_photo.setVisibility(View.VISIBLE);
            iv_back.setVisibility(View.VISIBLE);
            iv_close.setVisibility(View.GONE);
            iv_cut.setVisibility(View.VISIBLE);

            iv_image.setImageResource(0);
        } else if (id == R.id.tv_next) {

            DeleteFriends deleteFriends = new DeleteFriends("CarCut", imgFile.getPath(), carId, carNum);
            EventBus.getDefault().post(deleteFriends);
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    /**
     * 动态申请sdcard读写权限
     */
    private void autoObtainStoragePermission() {
        XXPermissions.with(this)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if(all){
                            Intent intent = new Intent(X3MainCarCutActivity.this, X3CameraPhotoActivity.class);
                            intent.putExtra("isAlbum",1);
                            intent.putExtra("allNum",1);
                            startActivity(intent);
                            overridePendingTransition(R.anim.activity_enter, 0);
                        }else {
                            XXPermissions.startPermissionActivity(X3MainCarCutActivity.this,permissions);
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        XXPermissions.startPermissionActivity(X3MainCarCutActivity.this,permissions);
                    }
                });
    }

    /**
     * 从相册中选取图片 或者拍照 数据都会从这个方法进入
     * @param cameraBean
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetPictureOrVideo(CameraBean cameraBean) {
        if (cameraBean == null) {
            return;
        }
        switch ((int) cameraBean.resultCode) {
            //相册返回 集合
            case X3Constent.CODE_GALLERY_REQUEST:
                if (cameraBean.cameraData == null) {
                    return;
                }
                List<String> pList = (List<String>) cameraBean.cameraData;
                if (X3StringUtils.isListEmpty(pList)) {
                    return;
                }

                String uploadPath = pList.get(0);
                DeleteFriends deleteFriends = new DeleteFriends("CarCut",uploadPath,carId,carNum);
                EventBus.getDefault().post(deleteFriends);
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("车款缩略图拍摄页");
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("车款缩略图拍摄页");
    }
}